//
//  XOauthViewController.swift
//  WeiBoReDo
//
//  Created by 放学跟鸽走 on 2017/4/9.
//  Copyright © 2017年 放学跟鸽走. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 授权登录页面
class XOauthViewController: UIViewController {
    lazy var webView:UIWebView = UIWebView()
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(XClient_id)&redirect_uri=\(XRedirect_uri)")
        webView.loadRequest(URLRequest(url: url!))
        webView.delegate = self
        
        
    }

    

}
// MARK: - webview代理方法实现
extension XOauthViewController:UIWebViewDelegate{
     func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.url?.absoluteString
            
            else{
                return false
        }
        if url.hasPrefix(XRedirect_uri){
            //如果没有code,说明用户取消了授权
            if request.url?.query?.hasPrefix("code=") == false
            {
                    close()
                    return false
            }
           let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
            XNetworkManager.shared.loadAccessToken(code: code, complete: {[weak self](isSuccess) in
                
                if isSuccess{
                    SVProgressHUD.showSuccess(withStatus: "登录成功")
                    NotificationCenter.default.post(name: NSNotification.Name.init(XUserLoginSuccessedNotification), object: nil)
                    
                    self?.close()
                }else{
                    SVProgressHUD.showError(withStatus: "登录失败，请重新登录")
                }
                
            })
        
            
            print(code)
            return false
        }
        print(url)
        return true
        
    }
}
fileprivate extension XOauthViewController{
    /// UI搭建
    func setupUI(){
        webView.frame = view.bounds
        view.addSubview(webView)
        webView.scrollView.bounces = false
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }
    
    @objc func close() {
        dismiss(animated: true, completion: nil)
        
    }
    @objc func autoFill(){
        let js = "document.getElementById('userId').value='17721302551';document.getElementById('passwd').value='xij085746'"
        webView.stringByEvaluatingJavaScript(from: js)
    }
}
